package com.pcg.posgasstation.view.fragments;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.pcg.posgasstation.R;
import com.pcg.posgasstation.adapter.OrderHistoryAdapter;
import com.pcg.posgasstation.base.BaseFragment;
import com.pcg.posgasstation.model.network.ApiClient;
import com.pcg.posgasstation.model.network.entity.BaseEntity;
import com.pcg.posgasstation.model.network.entity.HistoryOrderItemEntity;
import com.pcg.posgasstation.utils.ToastUtils;
import com.pcg.posgasstation.view.OrderDetailActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SearchOrderFragment extends BaseFragment {

    @BindView(R.id.swiperefresh)
    SwipeRefreshLayout mSwiperefresh;
    @BindView(R.id.rcvOrderHistory)
    RecyclerView mRcvOrderHistory;
    Unbinder unbinder;

    private OrderHistoryAdapter mAdapter;
    private int mPage = 1;

    private String mCurrentKeywords;

    public static SearchOrderFragment newInstance() {
        SearchOrderFragment fragment = new SearchOrderFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_history, container, false);
        unbinder = ButterKnife.bind(this, view);
        initViews();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void initViews() {
        initRecyclerView();
        mSwiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPage = 1;
                searchOrderByKeywords(mCurrentKeywords);
            }
        });
    }

    private void initRecyclerView() {
        List<HistoryOrderItemEntity> data = new ArrayList<>();

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        mAdapter = new OrderHistoryAdapter(R.layout.item_order_history, data);

        mRcvOrderHistory.setLayoutManager(layoutManager);
        mRcvOrderHistory.setAdapter(mAdapter);

        mAdapter.disableLoadMoreIfNotFullPage(mRcvOrderHistory);
        mAdapter.setEnableLoadMore(true);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRcvOrderHistory);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HistoryOrderItemEntity clickItemData = (HistoryOrderItemEntity) adapter.getItem(position);
                if (clickItemData == null) {
                    return;
                }
                OrderDetailActivity.startActivity(mContext, clickItemData.getOrder_sn(), false);
            }
        });

    }

    public void resetPage() {
        mPage = 1;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(getActivity());
            }

            if (mProgressDialog != null && mPage == 1) {
                mProgressDialog.show();
            }
        }
    }

    public void searchOrderByKeywords(String keywords) {
        mCurrentKeywords = keywords;

        if (TextUtils.isEmpty(mCurrentKeywords)) {
            refreshList(new ArrayList<HistoryOrderItemEntity>());
            return;
        }

        if (mPage == 1 && mProgressDialog != null) {
            mProgressDialog.show();
        }

        ApiClient.getApiService().getOrderList(ApiClient.getToken(), String.valueOf(mPage), keywords, null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity<List<HistoryOrderItemEntity>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseEntity<List<HistoryOrderItemEntity>> entity) {
                        setRefreshing(false);
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                        if (entity != null) {
                            if (entity.isSuccess()) {
                                List<HistoryOrderItemEntity> data = entity.getData();
                                if (data != null && !data.isEmpty()) {
                                    if (mPage == 1) {
                                        refreshList(data);
                                    } else {
                                        showList(data);
                                    }
                                } else {
                                    loadMoreEnd();
                                }
                            } else {
                                ToastUtils.showToast(entity.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        setRefreshing(false);
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void showList(List<HistoryOrderItemEntity> data) {
        mAdapter.addData(data);
        mAdapter.loadMoreComplete();
    }

    public void refreshList(List<HistoryOrderItemEntity> data) {
        mAdapter.replaceData(data);
        mAdapter.loadMoreComplete();
    }

    public void loadMoreEnd() {
        mAdapter.loadMoreEnd();
    }

    private void loadMore() {
        ++mPage;
        searchOrderByKeywords(mCurrentKeywords);
    }

    private void setRefreshing(boolean refreshing) {
        mSwiperefresh.setRefreshing(refreshing);
    }

}
